package com.atguigu.gmall.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.exception.GmallException;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.user.vo.LoginSuccessVo;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.user.entity.UserInfo;
import com.atguigu.gmall.user.service.UserInfoService;
import com.atguigu.gmall.user.mapper.UserInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 *
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService{

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public LoginSuccessVo login(UserInfo info) {

        LoginSuccessVo loginSuccessVo = new LoginSuccessVo();

        String loginName = info.getLoginName();
        String passwd = MD5.encrypt(info.getPasswd());

        UserInfo userInfo = lambdaQuery().eq(UserInfo::getLoginName, loginName).eq(UserInfo::getPasswd, passwd).one();

        if (userInfo == null){
            throw new GmallException(ResultCodeEnum.LOGIN_ERROR);
        }

        String token = UUID.randomUUID().toString().replace("-","");
        loginSuccessVo.setToken(token);
        loginSuccessVo.setUserId(userInfo.getId());
        loginSuccessVo.setNickName(userInfo.getNickName());

        redisTemplate.opsForValue().set(RedisConst.LOGIN_USER + token, JSON.toJSONString(userInfo),7, TimeUnit.DAYS);

        return loginSuccessVo;
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete(RedisConst.LOGIN_USER + token);
    }
}




